<template>
  <div class="profile-page">
    <a-page-header title="个人中心" sub-title="管理个人信息和账户设置" />

    <a-row :gutter="16">
      <!-- 左侧个人信息卡片 -->
      <a-col :span="8">
        <a-card class="profile-card card-shadow">
          <div class="profile-header">
            <div class="avatar-section">
              <a-upload
                :show-upload-list="false"
                :before-upload="beforeAvatarUpload"
                @change="handleAvatarChange"
              >
                <a-avatar :size="100" :src="userInfo.avatarUrl || defaultAvatar">
                  <template #icon><user-outlined /></template>
                </a-avatar>
                <div class="avatar-mask">
                  <camera-outlined style="font-size: 24px;" />
                </div>
              </a-upload>
            </div>
            
            <div class="user-basic-info">
              <h2>{{ userInfo.username }}</h2>
              <p class="role-tag">
                <a-tag :color="getRoleColor(userInfo.roles)">
                  {{ getRoleText(userInfo.roles) }}
                </a-tag>
              </p>
              <p class="user-id">ID: {{ userInfo.id }}</p>
            </div>
          </div>

          <a-divider />

          <div class="info-list">
            <div class="info-item">
              <mobile-outlined class="info-icon" />
              <span class="info-label">手机号：</span>
              <span class="info-value">{{ userInfo.mobile || '未绑定' }}</span>
            </div>
            <div class="info-item">
              <mail-outlined class="info-icon" />
              <span class="info-label">邮箱：</span>
              <span class="info-value">{{ userInfo.email || '未绑定' }}</span>
            </div>
            <div class="info-item">
              <calendar-outlined class="info-icon" />
              <span class="info-label">注册时间：</span>
              <span class="info-value">{{ formatDate(userInfo.createdAt) }}</span>
            </div>
            <div class="info-item">
              <clock-circle-outlined class="info-icon" />
              <span class="info-label">最后登录：</span>
              <span class="info-value">{{ formatDate(userInfo.lastLoginTime) }}</span>
            </div>
          </div>

          <a-divider />

          <a-space direction="vertical" style="width: 100%;" :size="12">
            <a-button type="primary" block @click="showEditModal = true">
              <template #icon><edit-outlined /></template>
              编辑资料
            </a-button>
            <a-button block @click="showPasswordModal = true">
              <template #icon><lock-outlined /></template>
              修改密码
            </a-button>
          </a-space>
        </a-card>

        <!-- 账户统计 -->
        <a-card class="stats-card card-shadow" style="margin-top: 16px;">
          <template #title>
            <bar-chart-outlined /> 账户统计
          </template>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-statistic 
                title="登录次数" 
                :value="stats.loginCount"
                :value-style="{ color: '#1890ff' }"
              />
            </a-col>
            <a-col :span="12">
              <a-statistic 
                title="在线时长" 
                :value="stats.onlineHours"
                suffix="小时"
                :value-style="{ color: '#52c41a' }"
              />
            </a-col>
          </a-row>
        </a-card>
      </a-col>

      <!-- 右侧详细信息 -->
      <a-col :span="16">
        <!-- 基本信息 -->
        <a-card class="info-card card-shadow">
          <template #title>
            <idcard-outlined /> 基本信息
          </template>
          <a-descriptions bordered :column="2">
            <a-descriptions-item label="用户名">
              {{ userInfo.username }}
            </a-descriptions-item>
            <a-descriptions-item label="账户状态">
              <a-tag :color="userInfo.status === 'ACTIVE' ? 'green' : 'red'">
                {{ userInfo.status === 'ACTIVE' ? '正常' : '禁用' }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="手机号">
              {{ userInfo.mobile || '未绑定' }}
              <a-button type="link" size="small" v-if="!userInfo.mobile">
                去绑定
              </a-button>
            </a-descriptions-item>
            <a-descriptions-item label="邮箱">
              {{ userInfo.email || '未绑定' }}
            </a-descriptions-item>
            <a-descriptions-item label="角色权限" :span="2">
              <a-space>
                <a-tag v-for="role in getRoles(userInfo.roles)" :key="role" :color="getRoleColor(role)">
                  {{ getRoleText(role) }}
                </a-tag>
              </a-space>
            </a-descriptions-item>
            <a-descriptions-item label="创建时间">
              {{ formatDate(userInfo.createdAt) }}
            </a-descriptions-item>
            <a-descriptions-item label="最后登录">
              {{ formatDate(userInfo.lastLoginTime) }}
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <!-- 安全设置 -->
        <a-card class="security-card card-shadow" style="margin-top: 16px;">
          <template #title>
            <safety-outlined /> 安全设置
          </template>
          <a-list :split="false">
            <a-list-item>
              <a-list-item-meta>
                <template #title>登录密码</template>
                <template #description>定期更换密码可以提高账户安全性</template>
              </a-list-item-meta>
              <template #actions>
                <a-button type="link" @click="showPasswordModal = true">
                  修改
                </a-button>
              </template>
            </a-list-item>
            <a-list-item>
              <a-list-item-meta>
                <template #title>手机绑定</template>
                <template #description>
                  {{ userInfo.mobile ? `已绑定手机：${userInfo.mobile}` : '未绑定手机号' }}
                </template>
              </a-list-item-meta>
              <template #actions>
                <a-button type="link">
                  {{ userInfo.mobile ? '更换' : '绑定' }}
                </a-button>
              </template>
            </a-list-item>
            <a-list-item>
              <a-list-item-meta>
                <template #title>邮箱绑定</template>
                <template #description>
                  {{ userInfo.email ? `已绑定邮箱：${userInfo.email}` : '未绑定邮箱' }}
                </template>
              </a-list-item-meta>
              <template #actions>
                <a-button type="link">
                  {{ userInfo.email ? '更换' : '绑定' }}
                </a-button>
              </template>
            </a-list-item>
          </a-list>
        </a-card>

        <!-- 操作日志 -->
        <a-card class="log-card card-shadow" style="margin-top: 16px;">
          <template #title>
            <history-outlined /> 最近操作
          </template>
          <a-timeline>
            <a-timeline-item v-for="log in recentLogs" :key="log.id" :color="log.color">
              <p style="margin: 0;">{{ log.action }}</p>
              <p style="margin: 0; font-size: 12px; color: #999;">{{ log.time }}</p>
            </a-timeline-item>
          </a-timeline>
        </a-card>
      </a-col>
    </a-row>

    <!-- 编辑资料弹窗 -->
    <a-modal
      v-model:open="showEditModal"
      title="编辑资料"
      width="600px"
      @ok="handleUpdateProfile"
    >
      <a-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="editForm.username" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="editForm.email" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item label="个人简介">
          <a-textarea 
            v-model:value="editForm.bio" 
            placeholder="请输入个人简介"
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 修改密码弹窗 -->
    <a-modal
      v-model:open="showPasswordModal"
      title="修改密码"
      width="500px"
      @ok="handleChangePassword"
    >
      <a-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="原密码" name="oldPassword">
          <a-input-password 
            v-model:value="passwordForm.oldPassword" 
            placeholder="请输入原密码"
          />
        </a-form-item>
        <a-form-item label="新密码" name="newPassword">
          <a-input-password 
            v-model:value="passwordForm.newPassword" 
            placeholder="请输入新密码"
          />
        </a-form-item>
        <a-form-item label="确认密码" name="confirmPassword">
          <a-input-password 
            v-model:value="passwordForm.confirmPassword" 
            placeholder="请再次输入新密码"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'
import {
  UserOutlined,
  CameraOutlined,
  EditOutlined,
  LockOutlined,
  MobileOutlined,
  MailOutlined,
  CalendarOutlined,
  ClockCircleOutlined,
  IdcardOutlined,
  SafetyOutlined,
  HistoryOutlined,
  BarChartOutlined
} from '@ant-design/icons-vue'

const userStore = useUserStore()
const defaultAvatar = 'https://api.dicebear.com/7.x/avataaars/svg?seed=admin'

// 用户信息
const userInfo = reactive({
  id: null,
  username: '',
  mobile: '',
  email: '',
  avatarUrl: '',
  roles: '',
  status: 'ACTIVE',
  createdAt: null,
  lastLoginTime: null
})

// 统计数据
const stats = reactive({
  loginCount: 0,
  onlineHours: 0
})

// 最近操作日志
const recentLogs = ref([
  { id: 1, action: '登录系统', time: '2025-10-27 14:30:00', color: 'green' },
  { id: 2, action: '查看反馈列表', time: '2025-10-27 14:25:00', color: 'blue' },
  { id: 3, action: '发送系统通知', time: '2025-10-27 14:20:00', color: 'blue' },
  { id: 4, action: '审核教员申请', time: '2025-10-27 14:15:00', color: 'blue' },
  { id: 5, action: '修改个人资料', time: '2025-10-27 10:00:00', color: 'blue' }
])

// 编辑资料
const showEditModal = ref(false)
const editFormRef = ref()
const editForm = reactive({
  username: '',
  email: '',
  bio: ''
})

const editRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在2-20个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 修改密码
const showPasswordModal = ref(false)
const passwordFormRef = ref()
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6-20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value !== passwordForm.newPassword) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ]
}

// 初始化
onMounted(() => {
  loadUserInfo()
  loadStats()
})

// 加载用户信息
const loadUserInfo = () => {
  const user = userStore.userInfo
  if (user) {
    Object.assign(userInfo, user)
    Object.assign(editForm, {
      username: user.username,
      email: user.email,
      bio: user.bio || ''
    })
  }
}

// 加载统计数据
const loadStats = () => {
  // TODO: 调用统计接口
  stats.loginCount = 156
  stats.onlineHours = 89
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理头像上传
const handleAvatarChange = (info) => {
  if (info.file.status === 'uploading') {
    return
  }
  if (info.file.status === 'done') {
    // 上传成功
    message.success('头像上传成功')
    // TODO: 更新头像URL
  }
}

// 更新个人资料
const handleUpdateProfile = async () => {
  try {
    await editFormRef.value.validate()
    // TODO: 调用更新接口
    message.success('资料更新成功')
    showEditModal.value = false
    loadUserInfo()
  } catch (error) {
    console.error('更新失败', error)
  }
}

// 修改密码
const handleChangePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    // TODO: 调用修改密码接口
    message.success('密码修改成功，请重新登录')
    showPasswordModal.value = false
    // 清空表单
    Object.assign(passwordForm, {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
  } catch (error) {
    console.error('修改密码失败', error)
  }
}

// 辅助方法
const getRoles = (roles) => {
  if (!roles) return []
  return roles.split(',').filter(r => r)
}

const getRoleColor = (role) => {
  if (!role) return 'default'
  if (role.includes('ADMIN')) return 'red'
  if (role.includes('TEACHER')) return 'blue'
  if (role.includes('PARENT')) return 'green'
  return 'default'
}

const getRoleText = (role) => {
  if (!role) return '未知角色'
  if (role.includes('ADMIN')) return '管理员'
  if (role.includes('TEACHER')) return '教员'
  if (role.includes('PARENT')) return '家长'
  return role
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}
</script>

<style lang="scss" scoped>
.profile-page {
  .card-shadow {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }

  .profile-card {
    .profile-header {
      text-align: center;
      padding: 20px 0;

      .avatar-section {
        position: relative;
        display: inline-block;
        margin-bottom: 20px;

        .avatar-mask {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          height: 35px;
          background: rgba(0, 0, 0, 0.4);
          border-radius: 0 0 50% 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          opacity: 0;
          transition: opacity 0.3s;
          cursor: pointer;
        }

        &:hover .avatar-mask {
          opacity: 1;
        }
      }

      .user-basic-info {
        h2 {
          margin: 12px 0 8px;
          font-size: 24px;
          font-weight: bold;
        }

        .role-tag {
          margin-bottom: 8px;
        }

        .user-id {
          color: #999;
          font-size: 14px;
          margin: 0;
        }
      }
    }

    .info-list {
      .info-item {
        display: flex;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .info-icon {
          font-size: 18px;
          color: #1890ff;
          margin-right: 12px;
        }

        .info-label {
          color: #666;
          min-width: 80px;
        }

        .info-value {
          color: #333;
          font-weight: 500;
        }
      }
    }
  }
}
</style>

